/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.networking;

/**
 * Creates an XML RPC request for sending to Wordpress servers.
 */
public class Request {

    /**
     * Request to be built
     */
    private String request = "";
    /**
     * A flag indicating whether a <struct> is being built.
     */
    private boolean structMode = false;

    /**
     * Constructor
     * @param method Method name
     */
    public Request(String method) {
        request = "<?xml version=\"1.0\"?>" +
                "<methodCall><methodName>" + method + "</methodName><params>";
    }

    /**
     * Adds a string parameter.
     * @param param
     */
    public void addStringParam(String param) {
        closeStruct();
        request += "<param><value><string>" + param + "</string></value></param>";
    }

    /**
     * Adds an integer parameter.
     * @param param
     */
    public void addIntParam(String param) {
        closeStruct();
        request += "<param><value><int>" + param + "</int></value></param>";

    }

    /**
     * Adds a struct member with a value.
     * @param name
     * @param value
     */
    public void addStructMember(String name, String value) {
        openStruct();
        request += "<member><name>" + name + "</name><value><string>" + value + "</string></value></member>";
    }

    /**
     * Opens the struct if not already open.
     */
    private void openStruct() {
        if (!structMode) {
            structMode = true;
            request += "<param><value><struct>";
        }
    }

    /**
     * Close the struct if not already closed.
     */
    private void closeStruct() {
        if (structMode) {
            structMode = false;
            request += "</struct></value></param>";
        }
    }

    /**
     * Returns the finished XML request.
     * @return
     */
    public String request() {
        closeStruct();
        return request += "</params></methodCall>";
    }
}
